package com.person.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;


/**
 * [数据库管理类，数据采用GreenDao来实现，所有实现通过模板自动生成；通过获取daoSession来获取所有的dao，从而实现操作对象]
 **/
public class DBManager {

    private static DBManager instance=null;
    private DaoMaster daoMaster=null;
    private DaoSession daoSession=null;
    private static DaoMaster.DevOpenHelper helper=null;
    private volatile static DBManager manager=null;
    private Context context;
    public SQLiteDatabase db;

    /**
     * [获取DBManager实例，单例模式实现]
     */
    public static DBManager getInstance(Context context) {
        //instance=null;
        if (manager == null) {
            synchronized (DBManager.class) {
                if (instance == null) {
                    instance = new DBManager(context);
                    manager=instance;
                }
            }
        }
        return instance;
    }

    /**
     * 构造方法
     */
    public DBManager(Context context) {

        if (daoSession == null) {
            if (daoMaster == null) {
                helper = new DaoMaster.DevOpenHelper(context, context.getPackageName(), null);
                db=helper.getWritableDatabase();
                daoMaster = new DaoMaster(db);
                daoSession = daoMaster.newSession();
            }
        }
    }




    public SQLiteDatabase getDb() {
        return db;
    }

    public DaoMaster getDaoMaster() {return daoMaster;}

    public void setDaoMaster(DaoMaster daoMaster) {
        this.daoMaster = daoMaster;
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }

    public void setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
    }

    /*
    * 使用完数据库，必须关闭数据库，以免造成资源浪费
    * */
    public void closeConnection(){
        closeHelper();
        closeDaoSession();
    }
    public void closeHelper(){
        if(helper!=null){
            helper.close();
            helper=null;
        }
    }
    public  void closeDaoSession(){
        if(daoSession!=null){
            daoSession.clear();
            daoSession=null;
        }
    }

}